package com.example.oj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.oj.entity.Competition;
import com.example.oj.entity.Question;
import com.example.oj.entity.User;
import com.example.oj.entity.dto.competition.CompetitionQueryRequest;
import com.example.oj.entity.dto.competition.CompetitionSaveRequest;
import com.example.oj.entity.dto.question.QuestionSaveRequest;
import com.example.oj.entity.vo.CompetitionVO;
import com.example.oj.entity.vo.QuestionVO;
import com.example.oj.entity.vo.UserVO;
import com.example.oj.service.CompetitionResultService;
import com.example.oj.service.CompetitionService;
import com.example.oj.mapper.CompetitionMapper;
import com.example.oj.service.QuestionService;
import com.example.oj.service.UserService;
import com.example.ojcommon.constant.UserConstant;
import com.example.ojcommon.enums.CompetitionEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 28651
 * @description 针对表【competition】的数据库操作Service实现
 * @createDate 2024-03-18 20:43:01
 */
@Service
public class CompetitionServiceImpl extends ServiceImpl<CompetitionMapper, Competition>
    implements CompetitionService {

  @Resource
  private CompetitionMapper competitionMapper;

  @Resource
  private UserService userService;

  @Resource
  private QuestionService questionService;

  @Resource
  private CompetitionResultService competitionResultService;

  @Override
  public List<Competition> getCompetitionPage(CompetitionQueryRequest queryRequest) {
    String name = queryRequest.getName();
    String order = queryRequest.getSortOrder();
    String sortField = queryRequest.getSortField();
    return competitionMapper.getCompetitionPage(name,order,sortField);
  }

  @Override
  public Page<CompetitionVO> getCompetitionVOPage(Page<Competition> competitionPage) {
    List<Competition> competitions = competitionPage.getRecords();
    Page<CompetitionVO> competitionVOPage = new Page<>(competitionPage.getCurrent(), competitionPage.getSize(), competitionPage.getTotal());
    if (CollectionUtils.isEmpty(competitions)) {
      return competitionVOPage;
    }
    List<CompetitionVO> collect = competitions.stream().map(this::getCompetitionVO).collect(Collectors.toList());
    competitionVOPage.setRecords(collect);
    return competitionVOPage;
  }

  @Override
  public CompetitionVO getCompetitionVO(Competition competition) {
    CompetitionVO competitionVO = new CompetitionVO();
    competitionVO.setQuestionNum(competition.getQuestionNum());
    User user = userService.getById(competition.getUserId());
    UserVO userVO = userService.getUserVO(user);
    competitionVO.setId(competition.getId());
    competitionVO.setUser(userVO);
    competitionVO.setName(competition.getName());
    competitionVO.setStartTime(competition.getStartTime());
    competitionVO.setEndTime(competition.getEndTime());
    competitionVO.setStartDateTime(competition.getStartTime());
    competitionVO.setEndDateTime(competition.getEndTime());
//        LocalDateTime now = LocalDateTime.now();
//        if(now.isBefore(competition.getStartTime())){
//            competitionVO.setStatusText(CompetitionEnum.NOT_STARTED.getText());
//        } else if(now.isAfter(competition.getEndTime())){
//            competitionVO.setStatusText(CompetitionEnum.OVER.getText());
//        } else {
//            competitionVO.setStatusText(CompetitionEnum.PROGRESS.getText());
//        }
    QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("competitionId", competition.getId());
    List<Question> list = questionService.list(queryWrapper);
    List<Long> collect = list.stream().map(Question::getId).collect(Collectors.toList());
    competitionVO.setQuestionList(collect);
    competitionVO.setStatus(competition.getStatus());
    competitionVO.setStatusText(CompetitionEnum.valueOf(competition.getStatus()).getText());
    competitionVO.setDescription(competition.getDescription());
    competitionVO.setCreateTime(competition.getCreateTime());
    return competitionVO;
  }

  @Override
  public List<QuestionVO> getQuestionListByCid(Long id) {
    QueryWrapper<Question> queryWrapper = new QueryWrapper<Question>();
    queryWrapper.eq(id != null, "competitionId", id);
    List<Question> list = questionService.list(queryWrapper);
    return list.stream().map(question -> {
      return questionService.getQuestionVO(question);
    }).collect(Collectors.toList());
  }

  @Override
  public Integer saveCompetition(CompetitionSaveRequest data, HttpServletRequest request) {
    Competition competition = new Competition();
    User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
    competition.setName(data.getName());
    competition.setQuestionNum(data.getQuestionList().size());
    competition.setUserId(user.getId());
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime startTime = LocalDateTime.parse(data.getStartTime(), formatter);
    LocalDateTime endTime = LocalDateTime.parse(data.getEndTime(), formatter);
    competition.setStartTime(startTime);
    competition.setEndTime(endTime);
    competition.setStatus(CompetitionEnum.NOT_STARTED.getValue());
    competition.setDescription(data.getDescription());
    Long id = data.getId();
    List<Long> questionList = data.getQuestionList();
    if (id != null) {
      // 如果id不为空就是修改
      competition.setId(data.getId());
      //先清除之前竞赛关联的题目
      questionService.removeCompetitionId(data.getId());
      //再更新新的题目
      questionService.updateCompetitionId(questionList, data.getId());
      return competitionMapper.updateById(competition);
    } else {
      int res = competitionMapper.insert(competition);
      questionService.updateCompetitionId(questionList, competition.getId());
      return res;
    }
  }

  @Override
  public Integer deleteCompetition(Long id) {
    questionService.removeCompetitionId(id);
    return competitionMapper.deleteById(id);
  }

  @Override
  public Integer updateCompetitionState(Long id, Integer state) {
    if (state == 3) {
      // 如果比赛已经结束，那就将题目的状态改为公开
      questionService.updateQuestionIsQueried(id);
      // 如果比赛已经结束，那生成排行榜
      competitionResultService.createResult(id);
    }
    return competitionMapper.updateCompetitionState(id, state);
  }

}




